package com.spring.common.web.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.common.collect.Maps;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.PartETag;
import com.mangofactory.swagger.annotations.ApiIgnore;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.CreateOSSClient;
import com.spera.aliyunUtil.SperaOSSUtil;
import com.spera.aliyunUtil.SperaPartETag;
import com.spera.genutil.tools;
import com.spring.appservice.web.service.MainShowService;
import com.spring.common.web.dao.CommonApiMapper;
import com.spring.common.web.requestModel.ProductPromotion;
import com.spring.common.web.service.CommonService;
import com.spring.iosservice.web.model.CourseMtsInfo;
import com.spring.iosservice.web.model.OssPartInfo;
import com.spring.nbrbt.tools.otherutil.PropertiesUtil;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.UDate;
import com.spring.security.filestream.config.Configurations;
import com.spring.security.filestream.util.TokenUtil;
import com.spring.security.web.controller.BaseController;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.service.MessageProvider;
import com.spring.tools.MyTools;
import com.wordnik.swagger.annotations.ApiOperation;

@Controller
@RequestMapping(value = "/common")
@ApiIgnore
public class CommonApiController extends BaseController{

	@Resource
	private CommonService commonService;
	
	@Resource
	private MongoTemplate mongoService;
	
	@Resource
	private JedisCache jedisCache;
	@Resource
	private MyTools myTools;	
	@Resource
	private MainShowService mainShowService;
	
	@Resource
	private CommonApiMapper commonApiMapper;
	
	@Resource
	private MessageProvider messageProvider;
	

	/**
	 * 获取所有区域信息
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getServiceIntroduction")
	@ResponseBody
	public Object getServiceIntroduction(String service_type_code,
			String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getServiceIntroduction(service_type_code);

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 获取所有区域信息
	 * 
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getRegionList")
	@ResponseBody
	public Object applyCard(String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getRegionList();

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 获取子区域信息
	 * 
	 * @param id
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getChildrenRegionList")
	@ResponseBody
	public Object getChildrenRegionList(String id, String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getChildrenRegionList(id);

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	/**
	 * 根据区域id获取乐园信息
	 * 
	 * @param id
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getKidsParkList")
	@ResponseBody
	public Object getKidsParkList(String id, String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {

			m = commonService.getKidsParkList(id);

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}

	@RequestMapping(value = "/getBaseCodeList")
	@ResponseBody
	public Object getBaseCodeList(String type, HttpServletRequest request,
			String callback) {
		Map<String, Object> m = commonService.getDataDictionaryList(type);
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	/**
	 * 获取OA前两级部门接口
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/queryDepartmentPark")
	@ResponseBody
	public Object queryDepartmentPark(String dept_id,String callback) {
		List<Map<String, Object>> m = commonService.queryDepartmentPark(dept_id);
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	/**
	 * 根据部门编号获取部门下面的用户
	 * @param callback
	 * priv_id:kewubu
	 * shopDeptId:门店编号
	 * dept_id:部门编号
	 * @return
	 */
	@RequestMapping(value = "/queryUserByDeptId")
	@ResponseBody
	public Object queryUserByDeptId(String dept_id,String shopDeptId,String priv_id,String callback) {
		List<Map<String, Object>> m = commonService.queryUserByDeptId(dept_id,shopDeptId,priv_id);
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	
	// 断点上传获取token
	@RequestMapping(value = "/uploadVideoTk")
	@ResponseBody
	public Object uploadVideoTk(HttpServletRequest req, HttpServletResponse resp,
			String file_name, String file_size,String token) throws ServletException,
			IOException {
		
		Map<String, Object> k = com.spera.genutil.TokenUtil.checkToken(token,jedisCache);
		if (ApplicationUtils.isNotNull(k)) {
			return k;
		}

//		String user_id = jedisCache.lindex(token,0);
		
		String file_token = TokenUtil.generateToken(file_name, file_size);
		Map<String, Object> jsonStr = new HashMap<String, Object>();
		jsonStr.put("file_token", file_token);
		List<Map<String, Object>> hasin = commonService.checkVideosToken(file_token);
		if (hasin!=null&&hasin.size()>0) {
			Map<String, Object> hasInFile = hasin.get(0);
			jsonStr.put("file_id", hasInFile.get("id"));
//			jsonStr.put("image_id", hasInFile.get("base_oss_fileid"));
			jsonStr.put(ApplicationUtils.STATUS, "1");
			jsonStr.put(ApplicationUtils.MSG, "附件已存在");
			return jsonStr;
		}
		
		if (!ApplicationUtils.isNotNull(file_name)) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "附件名不能为空");
			return jsonStr;
		}
		
		if (!ApplicationUtils.isNotNull(file_size)) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "未知附件大小");
			return jsonStr;
		}
		
//		boolean f = file_name.contains(".");
//		if(!f){
//			jsonStr.put(ApplicationUtils.STATUS, "0");
//			jsonStr.put(ApplicationUtils.MSG, "未知附件类型");
//			return jsonStr;
//		}
		
//		String fileType = file_name.substring(file_name.lastIndexOf(".")+1);
//		if(!"mp4".equalsIgnoreCase(fileType)){
//			jsonStr.put(ApplicationUtils.STATUS, "0");
//			jsonStr.put(ApplicationUtils.MSG, "该附件类型不支持");
//			return jsonStr;
//		}
		
	    int partCount = SperaOSSUtil.calPartCount(Long.parseLong(file_size));
        if (partCount < 1) {
        	jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "要上传文件的大小必须大于一个Part的字节数：" + AliyunContent.PART_SIZE);
			return jsonStr;
        }
		
		try {
			//第一次上传附件时，将获取到的token存入缓存(后续断点获取不需要写入缓存,只需调用uploadOssPos去获取)
			Query q = new Query(Criteria.where("id").is(file_token));
			OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
			if(ossPart==null){
				String filePath = "baseossfile_video_tmp/"+UDate.getDate()+"/"+file_token+".mp4";
				OSSClient client = CreateOSSClient.getInstance().getOSSClient();//
		    	String uploadId = SperaOSSUtil.initMultipartUpload(client, AliyunContent.inputBucket, filePath);
		    	OssPartInfo tokenObj = new OssPartInfo();
		    	tokenObj.setId(file_token);
		    	tokenObj.setFileSize(file_size);//文件大小
		    	tokenObj.setUploadId(uploadId);//上传请求id 
		    	tokenObj.setStartPos("0");//起始位置
		    	tokenObj.setStartPart("1");//起始partId
		    	tokenObj.setTotalPart(partCount+"");//附件上传任务总共分为多少片
		    	tokenObj.setFilepath(filePath);
		    	mongoService.insert(tokenObj);
			}
			
			if (Configurations.isCrossed())
				jsonStr.put("server", Configurations.getCrossServer());
			jsonStr.put(ApplicationUtils.STATUS, "1");
			jsonStr.put(ApplicationUtils.MSG, "成功");
		} catch (JSONException e) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "失败");
		}
		System.out.println("TokenServlet---->doGet--->json:" + jsonStr);
		return jsonStr;
	}

	// 断点上传获取pos
	@RequestMapping(value = "/uploadVideoPos")
	@ResponseBody
	public Object uploadVideoPos(HttpServletRequest req, HttpServletResponse resp,
			String file_token, String file_name, String file_size)
			throws ServletException, IOException {
		Map<String, Object> jsonStr = new HashMap<String, Object>();
		if(ApplicationUtils.isNotNull(file_token)){
			Query q = new Query(Criteria.where("id").is(file_token));
			OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
			if(ossPart!=null){
//			if (redisCache.exists(token)) {
				jsonStr.put("start",ossPart.getStartPos());///*redisCache.lindex(token, 2)*/
				jsonStr.put(ApplicationUtils.STATUS, "1");
				jsonStr.put(ApplicationUtils.MSG, "success");
			}else{
				jsonStr.put("start", null);
				jsonStr.put(ApplicationUtils.STATUS, "0");
				jsonStr.put(ApplicationUtils.MSG, "false");
			}
		}else{
			jsonStr.put("start", null);
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "false");
		}
		System.out.println("uploadpos---->doGet--->json:" + jsonStr);
		return jsonStr;
	}

	
	
	// 断点上传
	@RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadVideo(HttpServletRequest req, HttpServletResponse resp,
			String file_token,String file_name,String token,
			@RequestParam(value = "mp4file", required = true) MultipartFile mp4file)
			throws ServletException, IOException {
		
		Map<String, Object> k = com.spera.genutil.TokenUtil.checkToken(token,jedisCache);
		if (ApplicationUtils.isNotNull(k)) {
			return k;
		}

		String user_id = jedisCache.hget(token,com.spera.genutil.TokenUtil.USER_ID);
		
		Map<String, Object> jsonStr = new HashMap<String, Object>();

		if(!ApplicationUtils.isNotNull(file_token)){
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "token不能为空");
			return jsonStr;
		}
		
		Query q = new Query(Criteria.where("id").is(file_token));
		OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
		if(ossPart==null){
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "token已失效，请确认附件是否已上传完成");
			return jsonStr;
		}

		boolean success = false;
		String this_start = AliyunContent.PART_SIZE*(Integer.parseInt(ossPart.getStartPart()/*redisCache.lindex(token, 3)*/)-1)+"";
		String next_start = "0";
		String message = "success";
		OSSClient client = CreateOSSClient.getInstance().getOSSClient();
		try {
			
			PartETag eTag = SperaOSSUtil.uploadPartByByte(mongoService/*redisCache*/,ossPart.getFilepath(), ossPart.getUploadId()/*redisCache.lindex(token, 1)*/, client,
					mp4file.getInputStream(),mp4file.getSize(),Integer.parseInt(ossPart.getStartPart()/*redisCache.lindex(token, 3)*/));
			if(eTag!=null){
				success = true;
				next_start = (Long.parseLong(this_start)+mp4file.getSize())+"";
			}
		} catch (Exception se) {
			jsonStr.put("start", null);
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, message);
			
		} finally {
			//附件片段上传成功
			if(success){
				//更新redis
				mongoService.updateFirst(q, Update.update("startPos", next_start), OssPartInfo.class);
				//当前part与总part相比 // 传递完毕
				if (/*redisCache.lindex(token, 3)*/ossPart.getStartPart().equalsIgnoreCase(ossPart.getTotalPart()/*redisCache.lindex(token, 4)*/)) {
					//拼接eTag
					List<PartETag> eTags = new ArrayList<PartETag>();
					Query q_eTags = new Query(Criteria.where("token").is(ossPart.getFilepath()));
					List<SperaPartETag> SperaETags = mongoService.find(q_eTags, SperaPartETag.class);
					for(SperaPartETag se:SperaETags){
						PartETag e = new PartETag(se.getPartNumber(),se.geteTag());
						eTags.add(e);
					}
					CompleteMultipartUploadResult ret = SperaOSSUtil.completeMultipartUpload(client,AliyunContent.inputBucket,ossPart.getFilepath(),ossPart.getUploadId()/*redisCache.lindex(token, 1)*/,eTags);
					String file_id = ApplicationUtils.randomUUID();
					String image_uuid = ApplicationUtils.randomUUID();
					
					//清除redis
//					redisCache.del(token,token+"-etag");
					mongoService.remove(q_eTags, SperaPartETag.class);
					mongoService.remove(q, OssPartInfo.class);
					
					//MTS转码
					CourseMtsInfo cm = new CourseMtsInfo();
					cm.setTranscodeJobId("0");//待转码
					cm.setImgae_uuid(image_uuid);//封面id
					cm.setModelName("common");
					cm.setToken(file_token);
					cm.setEtag(ret.getETag());
					cm.setCourseVideosId(file_id);
					cm.setOssFilePath(ossPart.getFilepath());
					cm.setC_user_id(user_id);
					
					messageProvider.mtsProvider(cm);
					//mongoService.insert(cm);
					//先预插入表
					addOssFile(image_uuid);
					addOssViedoFile(file_id,image_uuid);
					jsonStr.put("file_id", file_id);
					jsonStr.put("image_id", image_uuid);
					
				}else{
					mongoService.updateFirst(q, Update.update("startPart", (Integer.parseInt(ossPart.getStartPart())+1)+""), OssPartInfo.class);
				}
				
				jsonStr.put("start", next_start);
				jsonStr.put(ApplicationUtils.STATUS, "1");
				jsonStr.put(ApplicationUtils.MSG, message);
				System.out.println("upload---->dopost--->json:" + jsonStr);
			}else{
				jsonStr.put("start", null);
				jsonStr.put(ApplicationUtils.STATUS, "0");
				jsonStr.put(ApplicationUtils.MSG, "第"+ossPart.getStartPart()/*redisCache.lindex(token, 3)*/+"部分上传失败");
			}
		}
		return jsonStr;
	}
	
	private void addOssFile(String image_uuid){
		Map<String,Object> im = new HashMap<String,Object>();
 		im.put("id", image_uuid);
 		im.put("url", PropertiesUtil.getProParm("app.myspace_video_default"));
 		commonService.addOssFile(im);
	}
	
	private void addOssViedoFile(String file_id,String image_uuid){
		Map<String,Object> im = new HashMap<String,Object>();
		im.put("id", file_id);
		im.put("image_id", image_uuid);
		commonService.addVideosFile(im);		
	}
	
	
	/**
	 * 图片断点上传获取token
	 * @param req
	 * @param resp
	 * @param file_name
	 * @param file_size
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadImageTk")
	@ResponseBody
	public Object uploadImageTk(HttpServletRequest req, HttpServletResponse resp,
			String file_name, String file_size,String token) throws ServletException,
			IOException {
		
		Map<String, Object> k = com.spera.genutil.TokenUtil.checkToken(token,jedisCache);
		if (ApplicationUtils.isNotNull(k)) {
			return k;
		}

//		String user_id = jedisCache.lindex(token,0);
		
		String file_token = TokenUtil.generateToken(file_name, file_size);
		Map<String, Object> jsonStr = new HashMap<String, Object>();
		List<Map<String, Object>> hasin = commonService.checkFilesToken(file_token);
//		int hasin = iosQuestService.checkImageFileToken(jsonStr);
		if (hasin != null&&hasin.size()>0) {
			Map<String, Object> hasInFile = hasin.get(0);
			jsonStr.put("file_id", hasInFile.get("id"));
			jsonStr.put(ApplicationUtils.STATUS, "1");
			jsonStr.put(ApplicationUtils.MSG, "附件已存在");
			return jsonStr;
		}
		
		if (!ApplicationUtils.isNotNull(file_name)) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "附件名不能为空");
			return jsonStr;
		}
		
		boolean f = file_name.contains(".");
		if(!f){
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "未知附件类型");
			return jsonStr;
		}
		
		String fileType = file_name.substring(file_name.lastIndexOf(".")+1);
		if(!"jpg".equalsIgnoreCase(fileType)&&!"jpeg".equalsIgnoreCase(fileType)&&
				!"png".equalsIgnoreCase(fileType)&&!"bmp".equalsIgnoreCase(fileType)){
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "该附件类型不支持");
			return jsonStr;
		}
		
		jsonStr.put("file_token", file_token);
	    int partCount = SperaOSSUtil.calPartCount(Long.parseLong(file_size));
        if (partCount < 1) {
        	partCount=1;
        }
		
		try {
			//第一次上传附件时，将获取到的token存入缓存(后续断点获取不需要写入缓存,只需调用uploadOssPos去获取)
			Query q = new Query(Criteria.where("id").is(file_token));
			OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
			if(ossPart==null){
				String filePath = "multiple_file_tmp/"+UDate.getDate()+"/"+file_token+"."+fileType;
				OSSClient client = CreateOSSClient.getInstance().getOSSClient();//
		    	String uploadId = SperaOSSUtil.initMultipartUpload(client, AliyunContent.inputBucket, filePath);
		    	OssPartInfo tokenObj = new OssPartInfo();
		    	tokenObj.setId(file_token);
		    	tokenObj.setFileSize(file_size);//文件大小
		    	tokenObj.setUploadId(uploadId);//上传请求id 
		    	tokenObj.setStartPos("0");//起始位置
		    	tokenObj.setStartPart("1");//起始partId
		    	tokenObj.setTotalPart(partCount+"");//附件上传任务总共分为多少片
		    	tokenObj.setFilepath(filePath);
		    	mongoService.insert(tokenObj);
			}
//			if (Configurations.isCrossed())
//				jsonStr.put("server", Configurations.getCrossServer());
			jsonStr.put(ApplicationUtils.STATUS, "1");
			jsonStr.put(ApplicationUtils.MSG, "成功");
		} catch (JSONException e) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "失败");
		}
		System.out.println("TokenServlet---->doGet--->json:" + jsonStr);
		return jsonStr;
	}

	// 图片断点上传获取pos
	@RequestMapping(value = "/uploadImagePos")
	@ResponseBody
	public Object uploadImagePos(HttpServletRequest req, HttpServletResponse resp,
			String file_token, String file_name, String file_size)
			throws ServletException, IOException {
		Map<String, Object> jsonStr = new HashMap<String, Object>();
		if(ApplicationUtils.isNotNull(file_token)){
			Query q = new Query(Criteria.where("id").is(file_token));
			OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
			if(ossPart!=null){
//			if (redisCache.exists(token)) {
				jsonStr.put("start",ossPart.getStartPos());///*redisCache.lindex(token, 2)*/
				jsonStr.put(ApplicationUtils.STATUS, "1");
				jsonStr.put(ApplicationUtils.MSG, "success");
			}else{
				jsonStr.put("start", null);
				jsonStr.put(ApplicationUtils.STATUS, "0");
				jsonStr.put(ApplicationUtils.MSG, "false");
			}
		}else{
			jsonStr.put("start", null);
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "false");
		}
		System.out.println("uploadImagePos---->doGet--->json:" + jsonStr);
		return jsonStr;
	}

	// 图片断点上传
	@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadImage(HttpServletRequest req, HttpServletResponse resp,
			String file_token,String file_name,String token,
			@RequestParam(value = "imagefile", required = true) MultipartFile imagefile)
			throws ServletException, IOException {
		
		Map<String, Object> k = com.spera.genutil.TokenUtil.checkToken(token,jedisCache);
		if (ApplicationUtils.isNotNull(k)) {
			return k;
		}

		String user_id = jedisCache.hget(token,com.spera.genutil.TokenUtil.USER_ID);
		
		Map<String, Object> jsonStr = new HashMap<String, Object>();

		if(!ApplicationUtils.isNotNull(file_token)){
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "token不能为空");
			return jsonStr;
		}
		
		Query q = new Query(Criteria.where("id").is(file_token));
		OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
		if(ossPart==null){
//		if (!redisCache.exists(token)) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "token已失效，请确认附件是否已上传完成");
			return jsonStr;
		}

		boolean success = false;
		//PartETag eTag=null;
		String this_start = AliyunContent.PART_SIZE*(Integer.parseInt(ossPart.getStartPart()/*redisCache.lindex(token, 3)*/)-1)+"";
		String next_start = "0";
		String message = "success";
		OSSClient client = CreateOSSClient.getInstance().getOSSClient();
		try {
			//上传
			PartETag eTag = SperaOSSUtil.uploadPartByByte(mongoService/*redisCache*/,ossPart.getFilepath(), ossPart.getUploadId()/*redisCache.lindex(token, 1)*/, client,
					imagefile.getInputStream(),imagefile.getSize(),Integer.parseInt(ossPart.getStartPart()/*redisCache.lindex(token, 3)*/));
			if(eTag!=null){
				success = true;
				next_start = (Long.parseLong(this_start)+imagefile.getSize())+"";
			}
		} catch (Exception se) {
			jsonStr.put("start", null);
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, message);
			
		} finally {
			//附件片段上传成功
			if(success){
				//更新redis
				mongoService.updateFirst(q, Update.update("startPos", next_start), OssPartInfo.class);
				//当前part与总part相比 // 传递完毕
				if (/*redisCache.lindex(token, 3)*/ossPart.getStartPart().equalsIgnoreCase(ossPart.getTotalPart()/*redisCache.lindex(token, 4)*/)) {
					//拼接eTag
					List<PartETag> eTags = new ArrayList<PartETag>();
					Query q_eTags = new Query(Criteria.where("token").is(ossPart.getFilepath()));
					List<SperaPartETag> SperaETags = mongoService.find(q_eTags, SperaPartETag.class);
					for(SperaPartETag se:SperaETags){
						PartETag e = new PartETag(se.getPartNumber(),se.geteTag());
						eTags.add(e);
					}
					
					CompleteMultipartUploadResult ret = SperaOSSUtil.completeMultipartUpload(client,AliyunContent.inputBucket,ossPart.getFilepath(),
							ossPart.getUploadId(),eTags);
					String file_id = ApplicationUtils.randomUUID();
					String file_url = "http://" + ret.getBucketName() + ".img-cn-hangzhou.aliyuncs.com/" + ret.getKey();
					Map<String,Object> im = new HashMap<String,Object>();
					im.put("id", file_id);
					im.put("bucket", ret.getBucketName());
					im.put("url", file_url);
					im.put("etag", ret.getETag());
					im.put("key", ret.getKey());
					im.put("token", file_token);
					im.put("file_type", "img");
					im.put("c_user_id", user_id);
					commonService.addOssFile(im);
					//清除mongodb
					mongoService.remove(q_eTags, SperaPartETag.class);
					mongoService.remove(q, OssPartInfo.class);
					jsonStr.put("file_id", file_id);
					jsonStr.put("file_src", file_url);
				}else{
					mongoService.updateFirst(q, Update.update("startPart", (Integer.parseInt(ossPart.getStartPart())+1)+""), OssPartInfo.class);
				}
				
				jsonStr.put("start", next_start);
				jsonStr.put(ApplicationUtils.STATUS, "1");
				jsonStr.put(ApplicationUtils.MSG, message);
				System.out.println("upload---->dopost--->json:" + jsonStr);
			}else{
				jsonStr.put("start", null);
				jsonStr.put(ApplicationUtils.STATUS, "0");
				jsonStr.put(ApplicationUtils.MSG, "第"+ossPart.getStartPart()/*redisCache.lindex(token, 3)*/+"部分上传失败");
			}
		}
		return jsonStr;
	}
	
	/**
	 * 
	 * @param bannerType
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/getBannerList")
	@ResponseBody
	public Object getBannerList(String bannerType, String callback) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {
			m = commonService.getBannerList(bannerType);
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	/**
	 * 图片单次上传
	 * @param req
	 * @param resp
	 * @param token
	 * @param imagefile
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadImageByFile", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadImageByFile(HttpServletRequest req, HttpServletResponse resp,
			String token,
			@RequestParam(value = "imagefile", required = true) MultipartFile imagefile)
			throws ServletException, IOException {
		
		Map<String, Object> m = com.spera.genutil.TokenUtil.checkToken(token,jedisCache);
		if (ApplicationUtils.isNotNull(m)) {
			return m;
		}else{
			m = Maps.newHashMap();
		}
		
		String fileType = tools.getFileType(imagefile.getName());
		if(StringUtils.isBlank(fileType)){
			fileType = tools.getFileType(imagefile.getOriginalFilename());
		}
		if(StringUtils.isBlank(fileType)){
			fileType = imagefile.getContentType();
		}
//		String fileType = imagefile.getContentType();
//		System.out.println(imagefile.getOriginalFilename()+","+imagefile.getName()+","+conType);
//		if(!ApplicationUtils.isNotNull(fileType)){
//			m.put(ApplicationUtils.STATUS, "0");
//			m.put(ApplicationUtils.MSG, "未知附件类型");
//			return m;
//		}
		
		if(StringUtils.isBlank(fileType)){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "附件格式有误");
			return m;
		}
		
		if(!tools.checkFileType(fileType,"jpg","jpeg","bmp","png","image/jpeg","image/png","image/jpg")){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "附件类型不允许");
			return m;
		}
		
		FileInputStream fi = (FileInputStream) imagefile.getInputStream();
		String md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fi));  
		String file_token = md5;
		
		List<Map<String, Object>> hasin = commonService.checkFilesToken(file_token);
//		int hasin = iosQuestService.checkImageFileToken(jsonStr);
		if (hasin != null&&hasin.size()>0) {
			Map<String, Object> hasInFile = hasin.get(0);
			m.put("file_id", hasInFile.get("id"));
			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "附件已存在");
			return m;
		}
		
		try {
			m = new HashMap<String, Object>();
			String user_id = jedisCache.hget(token,com.spera.genutil.TokenUtil.USER_ID);
			if (!imagefile.isEmpty()) {
				
				String newfilename = "common_"+file_token+"_"+imagefile.getName();
				double fileSize = 0.00;
				fileSize = (double) imagefile.getSize() / 1048576;
				
				String file_id = ApplicationUtils.randomUUID();
				if (fileSize <= 5) {
					String filePath = SperaOSSUtil.springFileUpOss(AliyunContent.fileBucket,"common_file/"+UDate.getDate()+"/"+newfilename, imagefile);
					Map<String,Object> im = new HashMap<String,Object>();
					im.put("id", file_id);
					im.put("bucket", AliyunContent.fileBucket);
					im.put("url", filePath);
					im.put("etag", "");
					im.put("key", "common_file/"+UDate.getDate()+"/"+newfilename);
					im.put("token", file_token);
					im.put("file_type", fileType);
					im.put("file_size", fileSize);
					im.put("file_name", imagefile.getOriginalFilename());
					im.put("c_user_id", user_id);
					commonService.addOssFile(im);
					m.put("file_id", file_id);
					m.put("image_src", filePath);
					m.put(ApplicationUtils.STATUS, "1");
					m.put(ApplicationUtils.MSG, "上传成功");
				} else {
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "上传的文件太大，文件大小不能超过5M");
					return m;
				}
			} else {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请选择上传的文件");
			}

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();
		}

		return m;
	}
	
	/**
	 * 根据oa用户获取该用户下面的所有客户
	 * @param oaUserId
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "/queryCustomerSelByOaUser")
	@ResponseBody
	public Object queryCustomerSelByOaUser(String oaUserId,String callback) {
		List<Map<String, Object>> m = commonService.queryCustomerSelByOaUser(oaUserId);
		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	
	
	
	@RequestMapping(value = "/fileCommit")
	@ResponseBody
	public Object fileCommit(MultipartFile file) {

		Map<String, Object> m = new HashMap<String, Object>();
		try {
			
			 m=myTools.commitFile2("common",file);
			
			//m = commonService.getRegionList();

		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

			return m;

	}

	@RequestMapping(value = "/getAppointmentList")
	@ResponseBody
	public Object getAppointmentList(String userName,String productTypeCode,String skip, String rows, String pageSize, String pageIndex,
			String EntityAvailableState,String callback) {
				
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			
			m = mainShowService.getAppointmentList(userName,productTypeCode,skip, rows, pageSize, pageIndex, EntityAvailableState);
				
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	
	
	@RequestMapping(value = "/getBusinessTypeCode")
	@ResponseBody
	public Object getBusinessTypeCode(String type,String callback) {
				
		Map<String, Object> m = new HashMap<String, Object>();
		List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
		//type为1直接返回list
		try {
			if(type!=null&&type.equals("1")){
				list=commonService.getBusinessTypeCode2();
				return list;
			}
			m = commonService.getBusinessTypeCode();		
				
		} catch (Exception e) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "系统异常");
			e.printStackTrace();

		}

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, m);
		} else {
			return m;
		}
	}
	
	
	@RequestMapping(value = "/getBusinessTypeCode2")
	@ResponseBody
	public Object getBusinessTypeCode2(String type,String callback) {
				
		List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();

		list=commonService.getBusinessTypeCode2();

		if (ApplicationUtils.isNotNull(callback)) {
			return new JSONPObject(callback, list);
		} else {
			return list;
		}
	}
	
	

	@ApiOperation(value = "更新修改优惠", httpMethod = "POST", response = Object.class, notes = "获取抽奖场次",produces = "application/json; charset=utf-8")
	@RequestMapping(value = "/saveOrUpdateProductPromotion",method=RequestMethod.POST)
	@ResponseBody
	public Object saveOrUpdateProductPromotion(@RequestBody ProductPromotion  productPromotion) {
				
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			
			m = commonService.saveOrUpdateProductPromotion(productPromotion);
				
		} catch (Exception e) {
			e.printStackTrace();
			return buildFailedResultInfo("系统异常",productPromotion.getCallback());		
		}
		return m;
	}
	

	 
	@ApiOperation(value = "确认用户是否已录指纹", httpMethod = "get", response = Object.class, notes = "获取抽奖场次",produces = "application/json; charset=utf-8")
	@RequestMapping(value = "/checkFingerExist",method=RequestMethod.GET)
	@ResponseBody
	public Object checkFingerExist(String c_user_id,String callback) {
				
		Map<String, Object> m = new HashMap<String, Object>();
		try {
			
			m = commonService.checkFingerExist(c_user_id);
				
		} catch (Exception e) {
			e.printStackTrace();
			return buildFailedResultInfo("系统异常",callback);		
		}
		return m;
	}
	
	@RequestMapping(value = "/updatePhone")
	@ResponseBody
	public Object updatePhone(String c_user_id,String oldPhone,String newPhone) {				
		try {
			return commonService.updatePhone(c_user_id,newPhone);
		} catch (Exception e) {			
			return MyTools.analyseError(e);
		} 
	}
	

}
